package com.wakala.employment.fragment.recruit;

import static com.xuexiang.xui.utils.XToastUtils.toast;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.faltenreich.skeletonlayout.Skeleton;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.wakala.employment.R;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentRecruitInfoBinding;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.ResumeInfoVo;
import com.wakala.employment.utils.ImageUtils;
import com.wakala.employment.widget.sharedialog.ShareDialog;
import com.wakala.employment.widget.sharedialog.bean.ShareData;
import com.wakala.employment.widget.sharedialog.interfaces.OnShareClick;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.utils.CollectionUtils;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import co.lujun.androidtagview.TagContainerLayout;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RecruitInfoFragment} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class RecruitInfoFragment  extends BaseFragment<FragmentRecruitInfoBinding> implements View.OnClickListener {

    private static final String TAG = RecruitInfoFragment.class.getSimpleName();
    /**
     * 简历信息ID
     */
    private Long resumeInfoId;

    private boolean hasCollect;
    /**
     * 简历信息对象
     */
    private ResumeInfoVo mResumeInfoVo;

    //private SkeletonScreen skeletonScreen;
    private Skeleton skeleton;
    /**
     * 自定义加载对话框
     */
    private CustomDialog customDialog = null;//搜索市等待对话框



    @NonNull
    @Override
    protected FragmentRecruitInfoBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentRecruitInfoBinding.inflate(inflater, container, attachToRoot);
    }


    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        StatusBarUtils.setStatusBarLightMode(getActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        requireActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return null;
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        if(null!=getArguments()){
            resumeInfoId = getArguments().getLong("resumeInfoId");
        }

    }

    @Override
    protected void initListeners() {
        super.initListeners();
        binding.llShare.setOnClickListener(this);
        binding.btnTopShare.setOnClickListener(this);
        binding.ssBtnKefu.setOnClickListener(this);
        binding.linkWorker.setOnClickListener(view -> callPhoneWithPermission((binding.linkWorker.getTag() == null ? "0" : binding.linkWorker.getTag().toString())));
        binding.ssBtnCollect.setOnClickListener(this);
    }

    @Override
    protected void initViews() {
        binding.smartRefresh.setEnableLoadMore(false);
        binding.ssBtnToBack.setOnClickListener(this);
        // Either use an existing Skeletonlayout
        skeleton = binding.skeletonLayout;
        skeleton.showSkeleton();
        initCustomDialog();
//        skeletonScreen = Skeleton.bind(binding.rootInfoView)
//                .load(R.layout.fragment_recruit_info_skeleton)
//                .duration(1000)
//                .color(R.color.shimmer_color)
//                .angle(20)
//                .shimmer(false)
//                .show();
        //加载接口数据
        getUserResumeInfo();
    }

    /**
     * 初始化加载对话框
     */
    private void initCustomDialog() {
        //初始化加载等待对话框
        customDialog = CustomDialog.build()
                .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_layout_spinkit) {
                    @Override
                    public void onBind(final CustomDialog dialog, View v) {

                    }
                });
    }

    @SuppressLint("CheckResult")
    private void getUserResumeInfo() {
        //skeletonScreen.show();
        customDialog.show();
        XHttpProxy.proxy(TestApi.IResumeService.class)
                .getByResumeInfoId(resumeInfoId)
                .subscribeWith(new NoTipRequestSubscriber<ResumeInfoVo>() {
                    @Override
                    protected void onSuccess(ResumeInfoVo resumeInfoVo) {
                        Log.i(TAG, "-------------招工信息详情------------------");
                        Log.i(TAG, GsonUtils.toJson(resumeInfoVo));
                        mResumeInfoVo = resumeInfoVo;
                        //skeletonScreen.hide();
                        Log.i(TAG, "-------------招工信息详情------------------");
                        //绑定数据到页面控件
                        bindData(mResumeInfoVo);
                        customDialog.dismiss();
                        skeleton.showOriginal();
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        Log.i(TAG, "-------------招工信息详情-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                        customDialog.dismiss();
                        //skeletonScreen.hide();
                    }

                });
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ssBtn_toBack) {
            popToBack();
        } else if (id == R.id.btn_top_share) {
            recruitShare();
        } else if (id == R.id.ll_share) {
            recruitShare();
        } else if(id == R.id.ssBtn_kefu){
            //linkKeFu();
            recruitShare();
        } else if (id == R.id.link_worker) {
            linkWorker();
        } else if (id == R.id.ssBtn_collect) {
            resumeCollect();
        }

    }

    /**
     * 界面控件数据绑定
     *
     * @param mResumeInfoVo
     */
    private void bindData(ResumeInfoVo mResumeInfoVo) {
        String s = JsonUtil.toJson(mResumeInfoVo);
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.color.color_f4)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(binding.imgUserAvatar.getContext()).load(mResumeInfoVo.getAvatar())
                .apply(options)
                .into(binding.imgUserAvatar);
        binding.tvNikeName.setText(mResumeInfoVo.getNickname());//修改个人信息
        binding.tvSex.setText(mResumeInfoVo.getSexName());//性别
        if (mResumeInfoVo.getAge() == 0) {
            binding.tvUserAge.setText("-");//年龄
        } else {
            binding.tvUserAge.setText(mResumeInfoVo.getAge() + "岁");//年龄
        }
        binding.rbJobState.setText(mResumeInfoVo.getJobStateName());//找活状态
        binding.tvUserNation.setText(mResumeInfoVo.getNation());//民族
        binding.tvUserIpRegion.setText(mResumeInfoVo.getIpRegion());//IP归属地
        binding.tvJobLinkPhone.setText(mResumeInfoVo.getJobLinkPhone());//简历联系电话
        binding.linkWorker.setTag(mResumeInfoVo.getJobLinkPhone()); //联系工人 保存简历电话
       // binding.tvJobHopeCategory.setText(mResumeInfoVo.getJobCategory());//求职意向
        TagContainerLayout mTagContainerLayout = (TagContainerLayout) findViewById(R.id.flowlayout_tgs);
        if(!CollectionUtils.isEmpty(mResumeInfoVo.getJobTags())){
            mTagContainerLayout.setTags(mResumeInfoVo.getJobTags());
        }
        if(StringUtils.isEmpty(mResumeInfoVo.getIntroduce())){
            binding.tvSummary.setText("暂无介绍");
        }else {
            binding.tvSummary.setText(mResumeInfoVo.getIntroduce());//个人介绍
        }

    }

    private void linkWorker(){

    }

    private void linkKeFu(){
        String appId = "wxe8a910123413ba65"; // 填移动应用(App)的 AppId
        IWXAPI api = WXAPIFactory.createWXAPI(requireContext(), appId);
        // 判断当前版本是否支持拉起客服会话
        if (api.getWXAppSupportAPI() >= Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
            WXOpenCustomerServiceChat.Req req = new WXOpenCustomerServiceChat.Req();
            req.corpId = "wwa201bef9182dd47e";							      // 企业微信 ID
            req.url = "https://work.weixin.qq.com/kfid/kfc1a000ec98182ebd4";	// 企业微信 客服URL
            api.sendReq(req);
        }else {
            toast("没有安装微信或版本太低");
        }
    }

    private void callPhoneWithPermission(String phoneNumber) {
        if (phoneNumber.equals("0")) {
            return;
        }
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.CALL_PHONE)
                // 设置权限请求拦截器（局部设置）
                //.interceptor(new PermissionInterceptor())
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            toast("获取部分权限成功，但部分权限未正常授予");
                            return;
                        }
                        //toast("获取录音和日历权限成功");
                        //startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phoneNumber)));
                        //startActivity(new Intent(Intent.ACTION_CALL_BUTTON));
                        CustomDialog.show(new OnBindView<CustomDialog>(R.layout.layout_custom_dial_phone_dialog) {
                            @Override
                            public void onBind(final CustomDialog dialog, View v) {
                                Button btnOk;
                                btnOk = v.findViewById(R.id.btn_ok);
                                ImageView imgClose = v.findViewById(R.id.img_close);
                                imgClose.setOnClickListener(view -> dialog.dismiss());
                                btnOk.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber)));
                                        dialog.dismiss();
                                    }
                                });
                            }
                        }).setMaskColor(getResources().getColor(R.color.translucent_background));
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            toast("被永久拒绝授权，请手动授予录音和日历权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getContext(), permissions);
                        } else {
                            toast("获取录音和日历权限失败");
                        }
                    }
                });
    }

    /**
     * 收藏处理
     */
    private void resumeCollect() {
        hasCollect = !hasCollect;
        //mJobInfoVo.getUserJobRecord().setHasCollect(!mJobInfoVo.getUserJobRecord().getHasCollect());
        Drawable dra = null;
        Resources res = getResources();
        if (hasCollect) {
            dra = res.getDrawable(R.drawable.icon_star_fill_king);

        } else {
            dra = res.getDrawable(R.drawable.icon_star_larger);
        }
        //调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
        dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
        binding.ssBtnCollect.setCompoundDrawables(null, dra, null, null);

        //
        //handleCollect(mJobInfoVo.getId());
    }

    /**
     * 分享处理
     */
    private void recruitShare() {
        List<ShareData> shareDataList = new ArrayList<>();
        shareDataList.add(new ShareData(getContext(), "微信", R.drawable.icon_wexin_cicly_round));
        shareDataList.add(new ShareData(getContext(), "朋友圈", R.drawable.icon_wexin_friend_round));
        shareDataList.add(new ShareData(getContext(), "复制链接", R.drawable.icon_link_round));
        shareDataList.add(new ShareData(getContext(), "生成海报", R.drawable.icon_poster_round));

        ShareDialog.build()
                .setShareDataList(shareDataList)
                .show(new OnShareClick() {
                    /*
                     * 此处为回调，
                     * @param context       返回上下文
                     * @param shareData     返回点击的 ShareData 实例
                     * @param shareButton   返回按钮
                     * @param index         返回索引
                     * @return 为 true 时，不自动关闭对话框
                     */
                    @Override
                    public boolean onClick(Context context, ShareData shareData, View shareButton, int index) {
                        //Toast.makeText(getContext(), shareData.getLabel() + " Click!", Toast.LENGTH_SHORT).show();
                        if(shareData.getLabel().equals("微信")){
                            try {
                                new ShareAction(getActivity())
                                        .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                                        .withText("河狸帮-招工找活")//分享内容
                                        .withMedia(new UMImage(getContext(), R.drawable.app_logo))
                                        .setCallback(umShareListener)//回调监听器
                                        .share();
                            }catch (Exception e){
                                Toast.makeText(getContext(), "分享失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }else if(shareData.getLabel().equals("朋友圈")){
                            new ShareAction(getActivity())
                                    .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                                    .withMedia(new UMImage(getContext(), R.drawable.app_logo))//传入平台
                                    .withText(getResources().getString(R.string.app_name))//分享内容
                                    .setCallback(umShareListener)//回调监听器
                                    .share();
                        } else if (shareData.getLabel().equals("复制链接")) {
                            Toast.makeText(getContext(), shareData.getLabel() + "已复制链接!", Toast.LENGTH_SHORT).show();
                        } else if (shareData.getLabel().equals("生成海报")) {
                            //ScreenshotUtil.getBitmapByView(getContext(), (ScrollView) findViewById(R.id.main_scrollview));
                            new XPopup.Builder(getContext()).asCustom(new BottomPopupView(requireContext()) {
                                @Override
                                protected int getImplLayoutId() {
                                    return R.layout.dialog_share_view;
                                }

                                @Override
                                protected void onCreate() {
                                    super.onCreate();
                                    findViewById(R.id.tvDismiss).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            dismiss();
                                        }
                                    });
                                    TextView tvWX = findViewById(R.id.tvWX);
                                    TextView tvWXFriends = findViewById(R.id.tvWXFriends);
                                    TextView tvDownCode = findViewById(R.id.tvDownCode);
                                    tvWX.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            shareWxImage();
                                            dismiss();
                                        }
                                    });
                                    tvWXFriends.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            shareWxFriendsImage();
                                            dismiss();
                                        }
                                    });
                                    tvDownCode.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            Bitmap originBitmap= BitmapFactory.decodeResource(getResources(),R.drawable.hlb_poster_bg01);
                                            ImageUtils.INSTANCE.saveImageToGallery(getContext(), originBitmap);
                                            dismiss();
                                        }
                                    });

                                }
                            }).show();
                        }
                        return false;
                    }
                });

    }
    public void shareWxImage() {
        new ShareAction(getActivity())
                .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台-微信好友
                .withText("河狸帮")//分享内容
                .withMedia(new UMImage(getContext(), R.drawable.hlb_poster_bg01))
                .setCallback(umShareListener)//回调监听器
                .share();
    }
    public void shareWxFriendsImage() {
        new ShareAction(getActivity())
                .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台-微信朋友圈
                .withText("河狸帮")//分享内容
                .withMedia(new UMImage(getContext(), R.drawable.hlb_poster_bg01))
                .setCallback(umShareListener)//回调监听器
                .share();
    }

    private final UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            Toast.makeText(getContext(), "分享开始", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(getContext(), "成功了", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(getContext(), "失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(getContext(), "取消了", Toast.LENGTH_LONG).show();

        }
    };
}